<template>
    <view class="main">
        <u-popup mode="center" :show="isShow" iconColor="white" @close="isShow = false" :closeable="!is_force" :closeOnClickOverlay="!is_force">
            <view class="flex-col-cen m-pop">
                <view class="po-rela mp-i-area">
                    <view class="mp-img">
                        <image :src="$cdn_img('/static/components/update/no-login-bg.png')" mode="widthFix"></image>
                    </view>
                </view>
                <u-gap height="10"></u-gap>
                <view class="mp-title u-m-b-20">版本升级，带给您新的体验</view>
                <view class="main-btn mp-btn" v-if="!isDown" @click="download_wgt">立即更新</view>
                <view class="sche-wrap" v-else>
                    <!-- 更新包下载中 -->
                    <view class="sche-bg">
                        <view class="sche-bg-jindu" :style="{ ...lengthStyle, width: innerWidth }"></view>
                    </view>
                    <text class="down-text">下载进度:{{ (downSize / 1024 / 1024).toFixed(2) }}M/{{ (fileSize / 1024 / 1024).toFixed(2) }}M</text>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
import { $cdn_img } from '@/common/utils/tool';
/**
 * 比较两个版本号
 * @param {string} v1 - 第一个版本号
 * @param {string} v2 - 第二个版本号
 * @returns {number} 如果v1 > v2返回1，v1 < v2返回-1，相等返回0
 */
function compareVersions(v1, v2) {
    // 将版本号分割为数字和预发布标识部分
    const parseVersion = (version) => {
        // 分离预发布标识（如-alpha, -beta等）
        const preReleaseIndex = version.indexOf('-');
        let mainVersion = version;
        let preRelease = '';

        if (preReleaseIndex !== -1) {
            mainVersion = version.substring(0, preReleaseIndex);
            preRelease = version.substring(preReleaseIndex + 1);
        }

        // 将主版本号分割为数字数组
        const parts = mainVersion.split('.').map((part) => {
            const num = parseInt(part, 10);
            return isNaN(num) ? 0 : num;
        });

        return {
            parts,
            preRelease
        };
    };

    const ver1 = parseVersion(v1);
    const ver2 = parseVersion(v2);

    // 比较主版本号部分
    const maxLength = Math.max(ver1.parts.length, ver2.parts.length);

    for (let i = 0; i < maxLength; i++) {
        const num1 = i < ver1.parts.length ? ver1.parts[i] : 0;
        const num2 = i < ver2.parts.length ? ver2.parts[i] : 0;

        if (num1 > num2) return 1;
        if (num1 < num2) return -1;
    }

    // 如果主版本号相同，比较预发布标识
    if (ver1.preRelease || ver2.preRelease) {
        // 如果只有一个有预发布标识，那么有预发布标识的版本较旧
        if (!ver1.preRelease && ver2.preRelease) return 1;
        if (ver1.preRelease && !ver2.preRelease) return -1;

        // 如果都有预发布标识，按字母顺序比较
        if (ver1.preRelease < ver2.preRelease) return 1;
        if (ver1.preRelease > ver2.preRelease) return -1;
    }

    return 0;
}

// console.log(compareVersions('1.0.2','1.0.2')>0)
export default {
    data() {
        return {
            $cdn_img,
            download_url: '',
            isShow: false,
            isDown: false, // 是否开始下载
            fileSize: 0, //文件大小
            downSize: 0, //已下载大小
            innerWidth: '',
            lengthStyle: {
                background: `#446CF1 url(${$cdn_img('/static/components/update/round.png')} ) center right 4rpx no-repeat`,
                backgroundSize: '26rpx 26rpx'
            },
            is_force: true // 是否强制更新 默认是
        };
    },
    created() {
        uni.$u.http.get('/api/update', {}).then((res) => {
            console.log('下载链接:::', res.data.url);
            this.is_force = res.is_force == 1; //是否为强更
            this.download_url = res.data.url;
			// console.log(compareVersions(res.data.version,'1.0.2')>0);
            // #ifdef APP-PLUS
            plus.runtime.getProperty(plus.runtime.appid, (widgetInfo = {}) => {
                console.log(`本地版本:${widgetInfo.version}`, res.data.version);
                if (compareVersions(res.data.version, widgetInfo.version)>0) {
                    this.download_url = res.data.url;
                    this.isShow = true;
                }
            });
            // #endif
        });
    },

    methods: {
        iSWgt() {
            return /\.wgt$/.test(this.download_url);
        },
        // 下载升级资源包
        download_wgt() {
            if (uni.$u.os() == 'ios') {
                // ios
                if (this.iSWgt()) {
                    //热更新
                    this.startLoader();
                } else {
                    //整包更新
                    let appleId = '';
                    plus.runtime.launchApplication({
                        action: `itms-apps://itunes.apple.com/cn/app/id${appleId}?mt=8`
                    });
                }
                return;
            } else {
                //安卓整包更新
                this.startLoader();
            }
        },
        startLoader() {
            this.isDown = true;
            const downloadTask = uni.downloadFile({
                url: this.download_url,
                success: (downloadResult) => {
                    if (downloadResult.statusCode === 200) this.installWgt(downloadResult.tempFilePath);
                }
            });
            downloadTask.onProgressUpdate((res) => {
                this.innerWidth = res.progress + '%';
                this.downSize = res.totalBytesWritten;
                this.fileSize = res.totalBytesExpectedToWrite;
            });
        },
        // 安装文件
        installWgt(path) {
            let vm = this;
            plus.runtime.install(
                path,
                {
                    force: true
                },
                function () {
                    // 应用资源下载完成！
                    if (vm.iSWgt()) plus.runtime.restart();
                },
                function (e) {
                    // 安装更新文件失败
                    uni.showModal({
                        content: '安装失败:' + JSON.stringify(e),
                        showCancel: false
                    });
                    // plus.nativeUI.alert("资源包解析失败，请稍后重试");
                    vm.isShow = false;
                }
            );
        }
        // 对比版本号
    }
};
</script>

<style lang="scss" scoped>
.m-pop {
    padding: 0 0 60rpx;
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 30rpx;

    .mp-i-area {
        height: 330rpx;
        background: $bg_color;
        width: 100%;
    }

    .mp-img {
        position: absolute;
        left: 0;
        right: 0;
        top: -100rpx;

        image {
            width: 100%;
            height: 100px;
        }
    }

    .mp-title {
        font-size: 24rpx;
        // font-weight: 600;
        color: #67686b;
        line-height: 36rpx;
        text-align: center;
    }

    .mp-btn {
        width: 400rpx;
        height: 72rpx;
    }
}

.sche-wrap {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-end;
    padding: 10rpx 50rpx 0;

    .sche-bg {
        position: relative;
        background-color: #e1e0e5;
        height: 30rpx;
        border-radius: 100px;
        width: 480rpx;

        .sche-bg-jindu {
            position: absolute;
            left: 0;
            top: 0;
            height: 30rpx;
            min-width: 30rpx;
            border-radius: 100px;
        }
    }

    .down-text {
        font-size: 24rpx;
        color: $main_color;
        margin-top: 16rpx;
    }
}
.main-btn {
    // 按钮
    margin: 0 auto;
    height: 80rpx;
    display: flex;
    color: #ffffff;
    font-size: 28rpx;
    line-height: 40rpx;
    border-radius: 40rpx;
    align-items: center;
    justify-content: center;
    background: linear-gradient(139deg, #a37337 0%, $bg_color 100%); // 按钮;
    box-shadow: rgba(206, 0, 29, 0.3); // 阴影颜色;
}
</style>
